package com.futuremap.ws.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.futuremap.ws.constant.API;
import com.futuremap.ws.ex.APIException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @FileName HttpCmd.java
 * @Description:
**/
public class HttpCmd {
    
	private static final Logger log = LoggerFactory.getLogger(HttpCmd.class);
	
	private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	
	private static OkHttpClient client = new OkHttpClient.Builder()
			        .connectTimeout(20, TimeUnit.SECONDS)
			        .writeTimeout(20, TimeUnit.SECONDS)
			        .readTimeout(20, TimeUnit.SECONDS)
			        .build();
	
	public static String runSendPost(String url, String json) throws IOException, APIException{

		String   result   =  "";
		Response response = null ;
		Request  request  = null ;
		try {
			long startTime = System.currentTimeMillis();
			RequestBody body = RequestBody.create(JSON,json);
			log.info("发送websocket处理请求:{}", url);
			request = new Request.Builder()
	                .url(url)
	                .post(body)
	                .build();
			response = client.newCall(request).execute();
			if(200 != response.code())
			{
				log.error("{}出错:code={},json={}",url,response.code(),json);
				throw new APIException(API.FAILED,API.MSG.get(API.FAILED));
			}
			result   = response.body().string();
			long endTime  = System.currentTimeMillis();
			log.info("花费时间："+(endTime-startTime));
			return result;
		} catch (IOException e) {
			log.error(e.getMessage());
			throw e;
		} finally {
			if(null != response){				
				response.body().close();
			}
		}
	}
	
	public static String runSendGet(String baseUrl, Map<String , String> params) throws IOException, APIException{
		String   result   =  "";
		Response response = null ;
		Request  request  = null ;
		try {
			long startTime = System.currentTimeMillis();
			String url = assemblyParameter(baseUrl,params);
			log.info("发送设备校验校验：{}"   , url);
			request = new Request.Builder().header("Content-Type"  , "application/json")
										   .addHeader("Accept"     , "application/json")
										   .addHeader("Connection" , "close")
										   .url(url)
										   .build();
			response = client.newCall(request).execute();
			if(200 != response.code())
			{
				log.error(url+"校验出错:code="+response.code());
				throw new APIException(API.IMEI_USER_VALID_ERR,API.MSG.get(API.IMEI_USER_VALID_ERR));
			}
			result   = response.body().string();
			long endTime  = System.currentTimeMillis();
			log.info("花费时间："+(endTime-startTime));
			return result;
		} catch (IOException e) {
			log.error(e.getMessage());
			throw e;
		} finally {
			if(null != response){				
				response.body().close();
			}
		}
	}
	

	private static String assemblyParameter(String baseUrl, Map<String, String> parameters) {
		StringBuilder para = new StringBuilder(baseUrl);
		if(null != parameters && parameters.size() > 0)
		{
			if(baseUrl.contains("?"))
			{
				para.append("&");
			}
			else
			{
				para.append("?");
			}
			for (String str : parameters.keySet()) {
				para.append(str).append("=").append(parameters.get(str)).append("&");
			}
			para.deleteCharAt(para.length()-1);
		}
		
		return para.toString();
	}
	
	public static void main(String[] args) {
		String url = "http://36.133.0.234:8280/tools/validationImei?ver=1&token=111";
		Map<String , String> params = new HashMap<String , String>();
		params.put("userId" , "74885");
//		params.put("uuid"   , "358740051010683");
		params.put("imei"   , "3516080804382161");
		try {
			//String s = runSendGet(url, params);
			String s = assemblyParameter(url,params);
			System.out.println(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
